﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BrokerBase.Lib.Person;
using System.Threading;
using BrokerBase.Lib.Core;
using BrokerBase.Lib.Query;
using NHibernate;

namespace Broker.View.PersonView
{
    /// <summary>
    /// HumanRelationListPage.xaml 的交互逻辑
    /// </summary>
    public partial class HumanRelationListPage : UserControl
    {
        private const int PAGE_SIZE = 10;

        private IPerson person;

        private PagingQuery pageingQuery;

        private string hqlBase = "from HumanRelation as r ";

        public HumanRelationListPage(IPerson person)
        {
            InitializeComponent();

            this.person = person;

            this.Loaded += new RoutedEventHandler(HumanRelationListPage_Loaded);
        }

        void HumanRelationListPage_Loaded(object sender, RoutedEventArgs e)
        {
            //this.Resources.Add("person", person);

            LoadRelationTypes();

            
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            if ((person as Person).Id == 0)
            {
                MessageBox.Show("请先保存客户资料后，再添加客户关系", "提示");
                return;
            }


            IHumanRelation relation = new HumanRelation();
            relation.RecordTime = DateTime.Now;
            relation.Person1 = person;

            HumanRelationForm frm = new HumanRelationForm(relation, Query,true);

            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = LibGlobal.MainWin;

            frm.ShowDialog();

        }

        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            ViewRelation();
        }

        private void benDel_Click(object sender, RoutedEventArgs e)
        {
            HumanRelation2 relation = gvHumanRelation.SelectedItem as HumanRelation2;

            if (relation != null)
            {
                if (MessageBox.Show("是否要删除[" + relation.HR.Person1.Name +"]和["+ relation.HR.Person2.Name  + "的关系]?", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    try
                    {
                        IBaseService<HumanRelation> service = new BaseService<HumanRelation>(LibGlobal.HbmSessionFactory.GetCurrentSession());

                        service.Delete(relation.HR as HumanRelation);

                        Query();

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }

        private void gvHumanRelation_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ViewRelation();
        }

        private void ViewRelation()
        {
            HumanRelation2 relation = gvHumanRelation.SelectedItem as HumanRelation2;

            if (relation != null)
            {
                HumanRelationForm frm = new HumanRelationForm(relation.HR, new Action(Query),true);

                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frm.Owner = LibGlobal.MainWin;

                frm.ShowDialog();
            }
        }

        private void LoadRelationTypes()
        {
            using (ISession sess = LibGlobal.HbmSessionFactory.OpenSession())
            {
                IList<IHumanRelationType> ls = sess.CreateQuery("from HumanRelationType").List<IHumanRelationType>();

                IHumanRelationType allType = new HumanRelationType();
                allType.Name = "[全部]";

                ls.Insert(0,allType);

                cmbRelationType.ItemsSource = ls;
            }
        }

        private void BuildQuery()
        {
            pageingQuery = new PagingQuery();

            string where = "where 1=1";

            if (person != null)
            {
                int id=(person as Person).Id;
                where += " and ( r.Person1.Id ="+id +" or r.Person2.Id="+id +" )";
            }

            HumanRelationType type = cmbRelationType.SelectedItem as HumanRelationType;

            if (type != null && type.Id>0)
            {
                where += " and r.RelationType.Id = " + type.Id;
            }

            pageingQuery.HQL = hqlBase + where + " order by r.RecordTime desc";
            pageingQuery.TotalHQL = "select count(*) " + hqlBase + where;
        }

        private void Query()
        {
            try
            {

                BaseService<HumanRelation> svr = new BaseService<HumanRelation>(LibGlobal.HbmSessionFactory.GetCurrentSession());
                long total = 0;
                if (pageingQuery == null)
                {
                    BuildQuery();
                }
                IList<HumanRelation> ls = svr.GetListByHQLWithPaging(pageingQuery.HQL, pageingQuery.TotalHQL, pageingQuery.FirstResult, PAGE_SIZE, out total);

                dpList.ItemCount = (int)total;

                IList<HumanRelation2> ls2 = new List<HumanRelation2>();

                foreach (IHumanRelation hr in ls)
                {
                    ls2.Add(new HumanRelation2(hr,person));
                }

                gvHumanRelation.ItemsSource = ls2;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void dpList_PageIndexChanged(object sender, Telerik.Windows.Controls.PageIndexChangedEventArgs e)
        {
            if (pageingQuery != null)
            {
                Query();
            }
        }

        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            BuildQuery();
            Query();
        }
    }

    class HumanRelation2
    {
        public IHumanRelation HR { get; set; }

        public IPerson PSelf{get;set;}

        public HumanRelation2(IHumanRelation hr,IPerson pSelf)
        {
            this.HR = hr;
            this.PSelf = pSelf;
        }

        public IPerson RelationPerson
        {
            get
            {
                return (PSelf as Person).Id == (HR.Person1 as Person).Id ? HR.Person2 : HR.Person1;
            }
        }

    }
}
